package com.wr.interceptor;

import com.wr.model.SessionEntity;
import com.wr.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class AuthenticateInterceptor implements HandlerInterceptor {

    @Autowired
    private SessionService sessionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(null == request.getSession().getAttribute("mobile")){
            response.sendRedirect("loginPage");
            return false;
        }
        if(sessionService != null){
            SessionEntity sessionEntity = sessionService.selectSessionByMobile((String) request.getSession().getAttribute("mobile"));
            //如果不为空
            if(sessionEntity != null){
                //如果sessionId不相等，则返回登录页面
                if(!request.getSession().getId().equals(sessionEntity.getSessionId())){
                    response.sendRedirect("loginPage");
                    return false;
                }
            } else {    //如果为空则插入
                sessionEntity = new SessionEntity();
                sessionEntity.setId(UUID.randomUUID().toString());
                sessionEntity.setMobile((String) request.getSession().getAttribute("mobile"));
                sessionEntity.setSessionId(request.getSession().getId());
                SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sessionEntity.setAddTime(sm.format(new Date()));
                sessionService.insertSessionEntity(sessionEntity);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
